import Slardar from '@slardar/sdk'

import { SlardarInstance } from './instance'

declare global {
  interface Window {
    Slardar: typeof import('@slardar/sdk').default
    loadScript: any
    loadLink: any
  }
}

export function triggerSlardar() {
  if (window.Slardar.shared!.instance.length === 0) {
    return
  }
  window.loadScript('https://m.toutiao.com/oncollect.js', () => {})
  window.loadLink('https://m.toutiao.com/oncollect.css', () => {})

  window.Slardar('Sentry', (Sentry: any) => {
    Sentry.captureMessage('ignore oncollect captureMessage')
  })

  window.Slardar('Sentry', (Sentry: any) => {
    Sentry.captureMessage('oncollect captureMessage')
  })

  window.Slardar('send', 'count', {
    category: 'cypress-oncollect',
    action: 'oncollect',
  })

  window.Slardar('send', 'timing', {
    category: 'cypress-oncollect',
    action: 'oncollect',
    value: 1358,
  })

  window.Slardar('emit', 'counter', {
    name: 'cypress-oncollect-counter',
    value: 1000,
    tags: {
      from: 'cypress-oncollect',
    },
  })

  Slardar('emit', 'counter', {
    name: 'cypress-oncollect-counter',
    value: 1000,
    tags: {
      from: 'cypress-oncollect',
    },
  })

  SlardarInstance('emit', 'counter', {
    name: 'cypress-oncollect-counter',
    value: 1000,
    tags: {
      from: 'cypress-oncollect',
    },
  })

  window.Slardar('emit', 'timer', {
    name: 'cypress-oncollect',
    value: 1000,
    tags: {
      from: 'cypress-oncollect',
    },
  })

  window.Slardar('emit', 'custom', {
    event_name: 'cypress',
    metrics: {
      'cypress-oncollect': 1000,
    },
    tags: {
      from: 'cypress-oncollect',
    },
  })

  window.Slardar('emit', 'log', {
    value: 'cypress-oncollect',
    level: 'debug',
    tags: {
      from: 'cypress-oncollect',
    },
  })

  sendFetch()
  sendXHR()
  sendSameOriginFetch()
  sendSameOriginXHR()
  sendNotSameOriginFetch()
  sendNotSameOriginXHR()
}

function sendFetch() {
  fetch('http://localhost:8080/oncollect/fetch')
}

function sendXHR(url?: string) {
  const oReq = new XMLHttpRequest()
  oReq.addEventListener('load', () => {})
  oReq.open('POST', url ?? 'http://localhost:8080/oncollect/xhr')
  oReq.send()
  oReq.timeout = 1000
}

function sendSameOriginFetch() {
  fetch('http://localhost:8080/oncollect/sameorigin/fetch')
}

function sendSameOriginXHR() {
  sendXHR('http://localhost:8080/oncollect/sameorigin/xhr')
}

function sendNotSameOriginFetch() {
  fetch('http://localhost:8081/oncollect/notsameorigin/fetch')
}

function sendNotSameOriginXHR() {
  sendXHR('http://localhost:8081/oncollect/notsameorigin/xhr')
}
